/**
 * File name:      PermissionManageManage.java
 * Date:           2013-4-12
 * Description:    // 用于详细说明此程序文件完成的主要功
 *                 // 能与其他模块或函数的接口，输出值、
 *                 // 取值范围、含义及参数间的关系
 * Modify History:     Date             Programmer       Notes
 *                    ---------        ---------------  ---------
 *                    2013-4-12            胡少磊                           Initial
 **********************************************************************/
package com.wy.framework.services.permission;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wy.framework.constants.DBConstant;
import com.wy.framework.exceptions.ServiceException;
import com.wy.framework.pojos.TSysRolepermissions;
import com.wy.framework.pojos.TSysUserinfo;
import com.wy.framework.services.AbstractBaseService;
import com.wy.component.dataConvert.BeanUtil;
import com.wy.component.dataConvert.DateUtil;

/**
 * Created on 2013-4-12
 * <p>Title:       [权限管理]</p>
 * <p>Description: [描述该类概要功能介绍]</p>
 * @version        1.0
 */
public class PermissionManageService extends AbstractBaseService {

	private static Logger logger = LoggerFactory
			.getLogger(PermissionManageService.class);

	/**
	 * 权限管理的Function ID
	 */
	private static String FUNCTION_D060 = "2e3b8816-b426-48f0-864d-871d485bf0ec";

	/**
	 * 	查询角色已有的权限信息		               
	*/

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List<Map> queryRolePermissions(String roleId)
			throws ServiceException {
		try {
			logger.info("查询用户拥有的功能");
			List<Map> roleFuns = getDataBaseDao().queryForList("T_Sys_Function.queryFunctionByRoleId", roleId);
			Map<String, Boolean> list = new HashMap<String, Boolean>();
			for (Map map1 : roleFuns) {
				list.put((String) map1.get("id"), true);
			}
			List<Map> functions = new ArrayList<Map>();
			logger.info("查询登录者拥有的功能");  
			if(loginUser().getUserId().equalsIgnoreCase("admin")){
				functions = getDataBaseDao().queryForList("T_Sys_Function.loadFunction");
			}else{
				List param = new ArrayList();
				param.add(loginUser().getUserId());	
				functions = getDataBaseDao().queryForList("T_Sys_UserRoles.queryFunctionByUser",param);
			}
			Set pIdSet= new HashSet(); 
			for(Map map :roleFuns){
				pIdSet.add(map.get("pid"));
			}
			// 判断角色是否拥有该功能
			for (Map map2 : functions) {
				if (list.get(map2.get("id")) != null && list.get(map2.get("id")) && !pIdSet.contains(map2.get("id"))) {
					map2.put("checked", true);
				}
			}
			return BeanUtil.listToTree(functions, "id", "pid");
		} catch (Exception e) {
			logger.error("系统错误:{}", e);
			throw new ServiceException(e);
		}
	}

	/**
	 * 查询角色信息			               
	*/

	@SuppressWarnings("unchecked")
	public List<Map> loadRoleInfo() throws ServiceException {
		try {
			List<Map> roleInfoMapList = new ArrayList<Map>();
    	    // 查询机构信息
    	    List param = new ArrayList();
    	    param.add(loginUser().getDept());
			return this.getDataBaseDao().queryForList("TC_Sys_OrgInfo.loadRoleInfo",param);
		} catch (Exception e) {
			logger.error("系统错误:{}", e);
			//e.printStackTrace();
			throw new ServiceException(e);
		}
	}
	
	
	//查询角色对应信息
	@SuppressWarnings("unchecked")
	public List<Map> queryRoleInfo(String roleId) throws ServiceException {
		try {
			// 查询机构信息
			return this.getDataBaseDao().queryForList("TcSysRoleInfo.queryRoleInfo",roleId);
		} catch (Exception e) {
			logger.error("系统错误:{}", e);
			throw new ServiceException(e);
		}
	}

	/**
	 * 保存角色权限信息				               
	*/
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void saveRolePermissions(String roleId, String functionIds)
			throws ServiceException {
		try {
			logger.info("角色的权限清单:{},{}", roleId, functionIds);
			// 系统管理员特殊处理
			if (roleId.equals(DBConstant.ROLE_R000)) {
				if (functionIds.indexOf(FUNCTION_D060) < 0) {
					logger.info("管理员:{}必须具有权限管理的权限:{}", roleId, FUNCTION_D060);
					if (functionIds.equals("")) {
						functionIds = FUNCTION_D060;
					} else {
						functionIds = functionIds + "," + FUNCTION_D060;
					}
				}
			}

			String[] ids = functionIds.split(",");
			logger.info("取消角色现有权限");
			List param=new ArrayList();
			param.add(DBConstant.DB_STATUS_DISABLCE);
			param.add(DateUtil.getCurrentDateTime());
			param.add(roleId);
			dataBaseDao.update("t_sys_rolepermissions.update",param);
			if (functionIds.equals("")) {
				logger.info("角色全部权限信息被取消!!");
				return;
			}
			for (String functionId : ids) {
				TSysRolepermissions rolePermissions = new TSysRolepermissions();
				rolePermissions.setRoleId(roleId);
				rolePermissions.setFunctionId(functionId);
				rolePermissions.setAuthorityId(UUID.randomUUID().toString());
				rolePermissions.flushUpdateTime();
				rolePermissions.setIsAvailable(DBConstant.DB_STATUS_ABLCE);
				rolePermissions.setOperatorName(loginUser().getUserName());
				logger.info("保存角色权限信息:{}", functionId);
				this.getDataBaseDao().save(rolePermissions);
			}
		} catch (Exception e) {
			logger.error("系统错误:{}", e);
			throw new ServiceException(e);
		}
	}

}
